package com.bjtg.threegoclinet.okhttpUtils;

import android.os.Handler;
import android.os.Looper;

import com.log.LatteLogger;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Request.Builder;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;

/**
 * OkHttpClient 工具类
 *
 * @author wdw
 */
public class OkHttpClientManager {
    /**
     * 请求时间
     */
    private static int TIMES = 30;
    private static OkHttpClientManager mInstance;
    private static OkHttpClient mOkHttpClient;
    private Handler mDelivery;

    /**
     * Context 用来清除xml数据
     */

    public OkHttpClientManager() {
        mOkHttpClient = new OkHttpClient();
        // 获取UI主线程
        mDelivery = new Handler(Looper.getMainLooper());
    }

    public static OkHttpClientManager getInstance() {
        if (mInstance == null) {
            synchronized (OkHttpClientManager.class) {
                if (mInstance == null) {
                    mInstance = new OkHttpClientManager();
                }
            }
        }
        return mInstance;
    }

    /**
     * 同步的Get请求
     *
     * @param url
     * @return Response
     */
    public Response getExecutEOkHttp(String url) throws IOException {
        final Request request = new Builder().url(url).build();
        Call call = mOkHttpClient.newCall(request);
        Response execute = call.execute();
        return execute;
    }

    /**
     * 同步的Get请求
     *
     * @param url
     * @return 字符串
     */
    public String getExecuteAsString(String url) throws IOException {
        Response execute = getExecutEOkHttp(url);
        return execute.body().string();
    }

    /**
     * 异步的get请求
     *
     * @param url
     * @param callback
     */
    public void postAsync(String url, final int code, Map<String, String> map,
                          final HttpCallback callback) {
        Builder mBuilder = new Builder();
        LatteLogger.d("Threego",url.toString());
        deliveryResult(callback, code, mBuilder.url(url).post(mapToParam(map)).build());
    }

    /**
     * 异步的post请求
     *
     * @param url
     * @param callback
     */
    public void postAsync(String url, final int code, HashMap<String, String> map, final HttpCallback callback,
                          int Times) {
        Builder mBuilder = new Builder();
        mOkHttpClient.setConnectTimeout(Times, TimeUnit.SECONDS);
        deliveryResult(callback, code, getRequest(mBuilder, url, map, callback));
    }

    private Request getRequest(Builder mBuilder, String url, HashMap<String, String> map, HttpCallback callback) {
        return mBuilder.url(url).post(mapToParam(map)).build();
    }

    private RequestBody mapToParam(Map<String, String> map) {

        FormEncodingBuilder builder = new FormEncodingBuilder();
        for (Entry<String, String> entry : map.entrySet()) {
            builder.add(entry.getKey(), entry.getValue());
        }
        return builder.build();
    }

    private void deliveryResult(final HttpCallback callback, final int code, Request request) {
        SendStart(code, callback);
        mOkHttpClient.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(final Request request, final IOException e) {
                LatteLogger.d("okHttp","failure");
                SendFailure(code, callback);
            }

            @Override
            public void onResponse(final Response response) {
                String string;
                try {
                    string = response.body().string();
                    SendSuccess(code, string, callback);
                    ResetOption();
                } catch (IOException e) {
                    e.printStackTrace();
                    SendFailure(code, callback);
                }

            }
        });
    }

    /**
     * 重置设置
     */
    public void ResetOption() {

        /**
         * 超时重置
         */
        if (mOkHttpClient.getConnectTimeout() == TIMES) {
        } else {
            mOkHttpClient.setConnectTimeout(TIMES, TimeUnit.SECONDS);
        }
    }

    /**
     * 开始
     *
     * @param code
     * @param callback
     */
    public void SendStart(final int code, final HttpCallback callback) {

        mDelivery.post(new Runnable() {

            @Override
            public void run() {

                callback.onStart(code);
            }
        });
    }

    /**
     * 成功
     *
     * @param code
     * @param
     * @param callback
     */
    public void SendSuccess(final int code, final String result, final HttpCallback callback) {

        mDelivery.post(new Runnable() {

            @Override
            public void run() {

                callback.onSuccess(result, code);
            }
        });
    }

    /**
     * 结束
     *
     * @param code
     * @param callback
     */
    public void SendFailure(final int code, final HttpCallback callback) {

        mDelivery.post(new Runnable() {

            @Override
            public void run() {

                callback.onFailure(code);
            }
        });
    }

    public interface HttpCallback {
        /**
         * @param result 回调参数
         * @param code   回调标记位
         */
        abstract void onSuccess(String result, int code);

        /**
         * @param code 回调标记位
         */
        abstract void onStart(int code);

        /**
         * @param code 回调标记位
         */
        abstract void onFailure(int code);

    }

}
